﻿/// <reference path="jquery.cookie.js" />
/// <reference path="jquery.min.js" />
//#region juery 扩展
$.extend({
    isN: function (o) { return typeof o == "number" },
    isInt: function (o) { return $.isN(o) && Math.round(o) == o },
    round: function (n, mantissa) { if (!mantissa) mantissa = 0; if (mantissa <= 0) return Math.round(n); var v = 1; for (var i = 0; i < mantissa; i++) v *= 10; return Math.round(n * v) / v; },
    formatMoney: function (num, n) {
        num = String(num.toFixed(n ? n : 2));
        var re = /(-?\d+)(\d{3})/;
        while (re.test(num)) num = num.replace(re, "$1,$2");
        return n ? num : num.replace(/^([0-9,]+\.[1-9])0$/, "$1").replace(/^([0-9,]+)\.00$/, "$1");;
    },
    formatMoneyToDeciamil: function(moneyStr) {
        return parseFloat(moneyStr.replace(",", ""));
        
    }
});
//#endregion


$.extend({
    jajax: function (obj) {
        var url, params, callback, errorHandler, type, async, dataType;
        url = obj.url;
        params = obj.params;
        callback = obj.callback;
        errorHandler = obj.errorHandler;
        type = obj.type;
        async = obj.async;
        dataType = obj.dataType;

        if (!url) throw new Error("url is undefined");
        type = type || "POST";
        async = async || true;
        dataType = dataType || "json";
        $.ajax({
            type: type,
            async: async,
            data: params,
            dataType: dataType,
            url: url,
            //contentType: "application/json;charset=utf-8",
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("isajax", "true");
                //$(".return_confrim").html("<img src='jquery/images/loading.gif'/>&nbsp;&nbsp;&nbsp;&nbsp;正在验证账户...");
            },
            success: function (d) {
                callback && callback(d);
            },
            error: function (e) {
                if (errorHandler) {
                    errorHandler(e);
                }
                else {
                    if (!e.responseText) {
                        $.loadend();
                        return;
                    }

                    if (JSON.parse(e.responseText).errorMessage) {
                        $.jAlert(JSON.parse(e.responseText).errorMessage);
                    } else {
                        $.jAlert(e.responseText);
                    }
                    $.loadend();
                }
            }
        });
    },
    jalert: function (message) {
        $.StockWindow({title:"提示", content: message,id:"MessageInfo-Window" });
    },
    submitForm: function (url, obj, options) {
        ///<summary>表单提交</summary>
        ///<param name=""></param>
        var defalut = { url: url, method: "post", target: "_self" };
        $.extend(true, defalut, options);
        var form = $("<form/>").attr("method", defalut.method).attr("action", defalut.url).attr("target", defalut.target).attr("autocomplete", "off").attr("onsubmit", "javascript:return true");
        $(document.body).append(form);
        for (var x in obj) {
            var input = $('<input type="hidden"/>').attr("name", x).val(obj[x]);
            form.append(input);
        }
        form.submit();
        //form.remove();
    },
    //#region cookie
    isLogin: function() {
        var c = $.cookie("qycf");
        if (!c) {
            return false;
        } else {
            return true;
        }
    }
    //#endregion
});
$.fn.uniqueId = function () {
    $(this).attr("id", "ui-" + (++self.id));
    return $(this);
};

//#region json

if (!this.JSON) { this.JSON = {}; }
(function () {
    function f(n) { return n < 10 ? '0' + n : n; }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
        }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
    function str(key, holder) {
        var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); }
        if (typeof rep === 'function') { value = rep.call(holder, key, value); }
        switch (typeof value) {
            case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; }
                gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; }
                    v = partial.length === 0 ? '[]' : gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v;
                }
                if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } }
                v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; }
            rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j; function walk(holder, key) {
                var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } }
                return reviver.call(holder, key, value);
            }
            cx.lastIndex = 0; if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; }
            throw new SyntaxError('JSON.parse');
        };
    }
}());

if (this.JSON && !this.JSON.parseWithDate) {
    var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
    var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
    // original var reMsAjax = /^\/Date\((d|-|.*)\)\/$/;

    JSON.parseWithDate = function (json) {
        /// <summary>
        /// parses a JSON string and turns ISO or MSAJAX date strings
        /// into native JS date objects
        /// </summary>
        /// <param name="json" type="var">json with dates to parse</param>
        /// </param>
        /// <returns type="value, array or object" />
        try {
            var res = JSON.parse(json,
            function (key, value) {
                if (typeof value === 'string') {
                    var a = reISO.exec(value);
                    if (a) {
                        if (a.length > 6) {
                            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
                        }
                        else {
                            return null;
                        }
                    }
                    a = reMsAjax.exec(value);
                    if (a) {
                        if (a.length > 0) {
                            var b = a[1].split(/[-+,.]/);
                            return new Date(b[0] ? +b[0] : 0 - +b[1]);
                        }
                        else {
                            return null;
                        }
                    }
                }
                return value;
            });
            return res;
        }
        catch (e) {
            // orignal error thrown has no error message so rethrow with message
            throw new Error("JSON content could not be parsed");
            return null;
        }
    };
    JSON.stringifyWcf = function (json) {
        /// <summary>
        /// Wcf specific stringify that encodes dates in the
        /// a WCF compatible format ("/Date(9991231231)/")
        /// Note: this format works ONLY with WCF.
        ///       ASMX can use ISO dates as of .NET 3.5 SP1
        /// </summary>
        /// <param name="key" type="var">property name</param>
        /// <param name="value" type="var">value of the property</param>
        return JSON.stringify(json, function (key, value) {
            if (typeof value == "string") {
                var a = reISO.exec(value);
                if (a) {
                    var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + '+0800)/';
                    //var val = '/Date(' + new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]).getTime() + ')/';
                    this[key] = val;
                    return val;
                }
            }
            return value;
        });
    };
    JSON.dateStringToDate = function (dtString) {
        /// <summary>
        /// Converts a JSON ISO or MSAJAX string into a date object
        /// </summary>
        /// <param name="" type="var">Date String</param>
        /// <returns type="date or null if invalid" />
        var a = reISO.exec(dtString);
        if (a)
            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
        a = reMsAjax.exec(dtString);
        if (a) {
            var b = a[1].split(/[-,.]/);
            return new Date(+b[0]);
        }
        return null;
    };
}
//#endregion

//#region 基础  
var win = function () { };
win.prototype.MinMoney = 2000;//最低金额
win.prototype.MaxMoney = 3000000;//最高金额
win.prototype.FirmCapital = 0;//实盘资金
win.prototype.RiskMargin = 0;//风险保证金
win.prototype.Type = 0;
win.prototype.ConfirmUrl = "/daywin/confirm";
win.prototype.Init = function (type) {
    var self = this;
    self.SlfTip = "最少2千，最多" + $.formatMoney(self.MaxMoney / 10000) + "万";
    self.Type = type;
    var $li = $("#CapitalSelect").find("li");
    if (self.Type == 0) {
        self.selectInit();
    } else {
        self.firminputInit();
    }

    $("#CapitalSelect").on("click", "li", function () {
        var $this = $(this);
        $li.removeClass("cur");
        $this.addClass("cur");
        self.Type = 0;
        self.FirmCapital = parseInt($this.attr("data"));
        if (self.FirmCapital < self.MinMoney) {
            self.FirmCapital = 0;
        }
        self.RiskMargin = self.getRiskMargin();
        self.moneyChange(self.FirmCapital);
        self.riskMarginChange(self.FirmCapital, self.RiskMargin);
        self.showLimit(self.FirmCapital);
        self.checkTodayShowable(self.FirmCapital);
    });
    $(":radio[name=RiskMargin]").bind("click", function () {
        self.RiskMargin = self.getRiskMargin();
        self.riskMarginChange(self.FirmCapital, self.RiskMargin);
        self.showLimit(self.FirmCapital, self.RiskMargin);
    });
    $("#InputFirmCapital").keypress(function (e) {
        var k = e.keyCode || e.which;
        if (k >= 48 && k <= 57 || k == 8) {
            return true;
        }
        return false;
    }).bind({
        "keyup": function () {
            var $this = $(this);
            var moneyStr = $.trim($this.val()).replace(/\,/g, "");
            if (!/^\d+$/.test(moneyStr)) {
                if (self.SlfTip != moneyStr) {
                    $this.val("");
                }
                return false;
            }

            var money = parseInt(moneyStr, 10);
            if (money > self.MaxMoney) {
                money = self.MaxMoney;
            }
            self.Type = 1;
            self.FirmCapital = money;
            self.RiskMargin = self.getRiskMargin();
            self.moneyChange(self.FirmCapital);
            self.riskMarginChange(self.FirmCapital, self.RiskMargin);
            self.showLimit(self.FirmCapital);
            self.checkTodayShowable(self.FirmCapital);
            $this.val($.formatMoney(money));
        }, "focusin": function () {
            var $this = $(this);
            $this.addClass("focusin").parent().addClass("focus");
            var moneyStr = $.trim($this.val()).replace(/\,/g, "");
            if (!/^\d+$/.test(moneyStr)) {
                $this.val("");
            }
        }, "focusout": function () {
            var $this = $(this);
            $this.parent().removeClass("focus");
            var moneyStr = $.trim($this.val()).replace(/\,/g, "");
            if (!/^\d+$/.test(moneyStr)) {
                $this.val(self.SlfTip);
                $this.removeClass("focusin");
            }
        }, "mouseover": function () {
            var $this = $(this);
            $this.parent().addClass("focus");
        }, "mouseout": function () {
            var $this = $(this);
            $this.parent().removeClass("focus");
        }
    });
    $("#FirmCapitalSelect").bind("click", function() {
        var $this = $(this);
        var cur = $this.attr("cur");
        var $FirmCapital = $("#FirmCapital");
        var $CapitalSelect = $("#CapitalSelect");
        if (cur == "select") {
            $this.attr("cur", "firminput");
            $this.html("选择实盘资金»");
            $FirmCapital.show();
            $CapitalSelect.hide();
            self.firminputInit();
        } else {
            $this.attr("cur", "select");
            $this.html("其他实盘资金»");
            $FirmCapital.hide();
            $CapitalSelect.show();
            self.selectInit();
        }
    });
    $("#WillStock").bind("click", function () {
        var data = self.getStockData();
        if (!data) {
            return;
        }
        $.submitForm(self.ConfirmUrl,data);
    });
};

win.prototype.selectInit = function () {
    var self = this;
    if ($("#CapitalSelect").find("li.cur").size() <= 0) {
        $("#CapitalSelect").find("li").eq(0).addClass("cur");
    }
    self.FirmCapital = parseInt($("#CapitalSelect").find("li.cur").attr("data"));
    self.RiskMargin = self.getRiskMargin();
    self.moneyChange(self.FirmCapital);
    self.riskMarginChange(self.FirmCapital, self.RiskMargin);
    self.showLimit(self.FirmCapital);
    self.checkTodayShowable(self.FirmCapital);
};
win.prototype.firminputInit = function () {
    var self = this;
    var moneyStr = $.trim($("#InputFirmCapital").val()).replace(/\,/g, "");
    if (!/^\d+$/.test(moneyStr)) {
        if (self.SlfTip != moneyStr) {
            $this.val("");
        }
        moneyStr = 0;
    }
    self.FirmCapital = parseInt(moneyStr);
    self.RiskMargin = self.getRiskMargin();
    self.moneyChange(self.FirmCapital);
    self.riskMarginChange(self.FirmCapital, self.RiskMargin);
    self.showLimit(self.FirmCapital);
    self.checkTodayShowable(self.FirmCapital);
};
win.prototype.getStockData = function() {
    var self = this;
    var riskMargin = $("input[name=RiskMargin]:checked").val();
    var totalTrade = $("#TotalTrade").html();
    var lossWarLine = $("#LossWarLine").html();
    var lossOpenLine = $("#LossOpenLine").html();
    var manageMoney = $("#ManageMoney").html();
    var startTime = $("input[name=StartTime]:checked").val();
    if (!self.FirmCapital) {
        $.jalert("请输入实盘资金");
        return false;
    }
    if (self.FirmCapital%1000>0) {
        $.jalert("实盘资金必须是1000的整数倍");
        return false;
    }
    if (self.FirmCapital < self.MinMoney || self.FirmCapital > self.MaxMoney) {
        $.jalert("实盘资金" + self.SlfTip);
        return false;
    }
    return {
        FirmCapital: self.FirmCapital,
        Type:self.Type,
        RiskMargin: $.formatMoneyToDeciamil(riskMargin),
        TotalTrade: $.formatMoneyToDeciamil(totalTrade),
        LossWarLine: $.formatMoneyToDeciamil(lossWarLine),
        LossOpenLine: $.formatMoneyToDeciamil(lossOpenLine),
        ManageMoney: $.formatMoneyToDeciamil(manageMoney),
        StartTime: parseInt(startTime),
        IsFree:0
    }
};
//计算风险保证金
win.prototype.MathRiskMargin = function (money,lever) {
    if ($.isInt(money) && $.isInt(lever)) {
        if (lever == 5 || lever == 10 || lever == 15) {
            if (lever == 5) {
                return { warning: money * 110 / 100, open: money * 107 / 100, principal: Math.floor(money / lever), fee: $.round(money * 1.2 / 1000, 4), interest: 1.2 };
            } else if (lever == 10) {
                return { warning: money * 106 / 100, open: money * 104 / 100, principal: Math.floor(money / lever), fee: $.round(money * 1.5 / 1000, 4), interest: 1.5 };
            }
            return { warning: money * 105 / 100, open: money * 103 / 100, principal: Math.floor(money / lever), fee: $.round(money * 2 / 1000, 4), interest: 2 };
        }
    }
    return { warning: 0, open: 0, principal: 0, fee: 0, interest: 0 };
}
//当金额改变时
win.prototype.moneyChange = function (money) {
    if (!$.isInt(money)) return;
    var self = this;
    var riskMargin15 = self.MathRiskMargin(money, 15);
    var riskMargin10 = self.MathRiskMargin(money, 10);
    var riskMargin5 = self.MathRiskMargin(money, 5);

    var $riskMargin15 = $("#RiskMargin15");
    var $riskMargin10 = $("#RiskMargin10");
    var $riskMargin5 = $("#RiskMargin5");

    $riskMargin15.parent().show();
    $riskMargin10.parent().show();
    $riskMargin5.parent().show();

    $riskMargin15.next().text($.formatMoney(riskMargin15.principal));
    $riskMargin10.next().text($.formatMoney(riskMargin10.principal));
    $riskMargin5.next().text($.formatMoney(riskMargin5.principal));

    if (money >= 50000) {
        $riskMargin15.next().css("font-size", "16px");
        $riskMargin10.next().css("font-size", "16px");
        $riskMargin5.next().css("font-size", "16px");
    } else {
        $riskMargin15.next().css("font-size", "20px");
        $riskMargin10.next().css("font-size", "20px");
        $riskMargin5.next().css("font-size", "20px");
    }
    if (money > self.rm15) {
        $riskMargin15.parent().hide();
    }
    if (money > self.rm10) {
        $riskMargin10.parent().hide();
    }
};
win.prototype.riskMarginChange = function (money, rm) {
    var self = this;
    var info = self.MathRiskMargin(money, rm);
    if (info != null) {
        $("#TotalTrade").text(money > 0 ? $.formatMoney($.round(money + info.principal, 0)) : "0");
        $("#LossWarLine").text($.formatMoney($.round(info.warning, 0)));
        $("#LossOpenLine").text($.formatMoney($.round(info.open, 0)));
        $("#ManageMoney").text($.formatMoney(info.fee));
    }
};
win.prototype.showLimit = function (money) {
    var info = this.getLimit(money, this.getRiskMargin());
    if (info && info != "") {
        $("#noneLimit").hide();
        $("#limit").show().css("color", "#cd1818");
        $("#limitinfo").html(info).parent().css("line-height", "25px");
    } else {
        $("#noneLimit").show();
        $("#limit").hide();
        $("#limitinfo").html("").parent().css("line-height", "50px");
    }
};
//检测仓位限制
win.prototype.getLimit = function (money,rm) {
    if ($.isNumeric(money) && $.isNumeric(rm)) {
        if (rm == 5) {
            if (money <= 500000) {
                return "";
            } else if (money <= 1000000) {
                return "单股不超总操盘资金的50%";
            } else {
                return "单股不超总操盘资金的50%（创业板33%）";
            }
        } else if (rm == 10) {
            if (money <= 200000) {
                return "";
            } else if (money <= 1000000) {
                return "单股不超总操盘资金的50%";
            }
        } else if (rm == 15) {
            if (money <= 100000) {
                return "";
            } else {
                return "单股不超总操盘资金的50%";
            }
        }
    }
    return "";
};
win.prototype.getRiskMargin = function () {
    return parseInt($(":radio[name=RiskMargin]:checked").val());
};
win.prototype.checkTodayShowable = function (money) {
    var tday = $("#tday");
    if (money < 1000000) {
        if (tday.size() > 0) {
            tday.parent().show();
        }
    } else {
        if (tday.length > 0) {
            tday.parent().hide();
            $("#NextTrader").click();
        }
    }
};
//#endregion

//#region 天天赢
var daywin = new win();
daywin.rm15 = 300000;
daywin.rm10 = 1000000;
//#endregion

//#region 周周盈
var weekwin = new win();
weekwin.ConfirmUrl = "/weekwin/confirm";
weekwin.getStockData = function() {
    var self = this;
    var riskMargin = $("#RiskMargin").html();
    var totalTrade = $("#TotalTrade").html();
    var lossWarLine = $("#LossWarLine").html();
    var lossOpenLine = $("#LossOpenLine").html();
    var manageMoney = 0;
    var startTime = $("input[name=StartTime]:checked").val();
    if (!self.FirmCapital) {
        $.jalert("请输入实盘资金");
        return false;
    }
    if (self.FirmCapital % 1000 > 0) {
        $.jalert("实盘资金必须是1000的整数倍");
        return false;
    }
    if (self.FirmCapital < self.MinMoney || self.FirmCapital > self.MaxMoney) {
        $.jalert("实盘资金" + self.SlfTip);
        return false;
    }
    return {
        FirmCapital: self.FirmCapital,
        Type: self.Type,
        RiskMargin: $.formatMoneyToDeciamil(riskMargin),
        TotalTrade: $.formatMoneyToDeciamil(totalTrade),
        LossWarLine: $.formatMoneyToDeciamil(lossWarLine),
        LossOpenLine: $.formatMoneyToDeciamil(lossOpenLine),
        ManageMoney: 0,
        StartTime: parseInt(startTime),
        IsFree: 0
    }
};
weekwin.MathRiskMargin = function (money) {
    if ($.isInt(money)) {
        return { warning: money * 110 / 100, open: money * 107 / 100, principal: Math.floor(money / 5), fee: $.round(money * 1.2 / 1000, 4), interest: 1.2 };
    }
    return { warning: 0, open: 0, principal: 0, fee: 0, interest: 0 };;
};
weekwin.moneyChange = function (money) {
    if (!$.isInt(money)) return;
    var self = this;
    var riskMargin= self.MathRiskMargin(money);
    var $riskMargin = $("#RiskMargin");
    $riskMargin.text($.formatMoney(riskMargin.principal));
    $("#TotalTrade").text(money > 0 ? $.formatMoney($.round(money + riskMargin.principal, 0)) : "0");
    $("#LossWarLine").text($.formatMoney($.round(riskMargin.warning, 0)));
    $("#LossOpenLine").text($.formatMoney($.round(riskMargin.open, 0)));
    $("#ManageMoney").text($.formatMoney(riskMargin.fee));
};
weekwin.riskMarginChange = function () { };
weekwin.getLimit = function (money) {
    if ($.isNumeric(money)) {
        if (money <= 500000) {
            return "";
        } else if (money <= 1000000) {
            return "单股不超总操盘资金的50%";
        } else {
            return "单股不超总操盘资金的50%（创业板33%）";
        }
    }
    return "";
}
//#endregion

//#region 股票配资
var tradewin = new win();
tradewin.MinMoney = 3000;//最低金额
tradewin.MaxMoney = 5000000;//最高金额
tradewin.Principal = 0;//投资本金
tradewin.MatchEndowment = 0;//配资金额
tradewin.interest = 0;
tradewin.ConfirmUrl = "/stock/confirm";
tradewin.Init = function(vmoney,vcur) {
    var self = this;
    self.SlfTip = "请输入投资本金，最少3千，最多" + $.formatMoney(self.MaxMoney / 10000) + "万";
    if (vmoney > 0) {
        $("#CapitalSelect").show();
        $("#CapitalInfo").hide();
        self.Principal = vmoney; //投资本金
        self.moneyChange(self.Principal, vcur);
    }
    $("#InputFirmCapital").keypress(function(e) {
        var k = e.keyCode || e.which;
        if (k >= 48 && k <= 57 || k == 8) {
            return true;
        }
        return false;
    }).bind({
        "keyup": function() {
            var $this = $(this);
            var moneyStr = $.trim($this.val()).replace(/\,/g, "");
            if (!/^\d+$/.test(moneyStr)) {
                if (self.SlfTip != moneyStr) {
                    $this.val("");
                }
                return false;
            }

            var money = parseInt(moneyStr, 10);
            if (money > self.MaxMoney) {
                money = self.MaxMoney;
            }
            self.Principal = money;//投资本金

            self.moneyChange(self.Principal);

            $this.val($.formatMoney(money));
        },
        "focusin": function() {
            var $this = $(this);
            $this.addClass("focusin").parent().addClass("focus");
            var moneyStr = $.trim($this.val()).replace(/\,/g, "");
            if (!/^\d+$/.test(moneyStr)) {
                $this.val("");
                $("#CapitalSelect").show();
                $("#CapitalInfo").hide();
            }
        },
        "focusout": function() {
            var $this = $(this);
            $this.parent().removeClass("focus");
            var moneyStr = $.trim($this.val()).replace(/\,/g, "");
            if (!/^\d+$/.test(moneyStr)) {
                $this.val(self.SlfTip);
                $this.removeClass("focusin");
                $("#CapitalSelect").hide();
                $("#CapitalInfo").show();
            }
        },
        "mouseover": function() {
            var $this = $(this);
            $this.parent().addClass("focus");
        },
        "mouseout": function() {
            var $this = $(this);
            $this.parent().removeClass("focus");
        }
    });

    var $li = $("#CapitalSelect").find("li");
    $("#CapitalSelect").on("click", "li:not(.disable)", function () {
        var $this = $(this);
        $li.removeClass("cur");
        $this.addClass("cur");
        self.moneyChange(self.Principal);
    });
    $("#WillStock").bind("click", function () {
        var data = self.getStockData();
        if (!data) {
            return;
        }
        $.submitForm(self.ConfirmUrl, data);
    });
};
tradewin.moneyChange = function (principal,cur) {
    var self = this;

    if ($.isInt(principal)) {
        principal = parseInt(principal, 10);
        var p = $.round(principal / 10000, 8);
        var $CapitalSelect = $("#CapitalSelect").find("li");
        $CapitalSelect.eq(0).attr("data",1).find("em").html(p * 3 >= 1 ? $.formatMoney(p * 1) + "万" : $.formatMoney(principal * 1));
        $CapitalSelect.eq(1).attr("data",2).find("em").html(p * 3 >= 1 ? $.formatMoney(p * 2) + "万" : $.formatMoney(principal * 2));
        $CapitalSelect.eq(2).attr("data",3).find("em").html(p * 3 >= 1 ? $.formatMoney(p * 3) + "万" : $.formatMoney(principal * 3));
        $CapitalSelect.eq(3).attr("data",4).find("em").html(p * 3 >= 1 ? $.formatMoney(p * 4) + "万" : $.formatMoney(principal * 4));
        $CapitalSelect.eq(4).attr("data", 5).find("em").html(p * 3 >= 1 ? $.formatMoney(p * 5) + "万" : $.formatMoney(principal * 5));

        if (cur) {
            $CapitalSelect.removeClass("cur");
            $CapitalSelect.filter("[data=" +(cur  /principal)  + "]").addClass("cur");
        }
        var lever = $.trim($CapitalSelect.filter(".cur").attr('data'));//配资金额
        var cycle = $("#Cycle").val();//资金使用期限
        var money = principal * lever;

        for (var i = 0; i < 5; i++) {
            var n = i + 1;
            var c = self.getScheme(principal * n, cycle, n, self.interest * 100);
            if (c.discount) {
                $CapitalSelect.eq(i).find("p").attr("class", "yh" + Math.round(c.interest / 10));
            } else {
                $CapitalSelect.eq(i).find("p").attr("class", "");
            }
        }

        var cfg = self.getScheme(money, cycle, lever, self.interest * 100);
        $("#TotalTrade").text($.formatMoney(money + principal));
        $("#LossOpenLine").text($.formatMoney(cfg.openLine));
        $("#LossWarLine").text($.formatMoney(cfg.warningLine));
        $("#LoanMoon").text($.formatMoney($.round(cfg.interest / 100.0, 2)));//借款月利率

        self.showLimit(money);
        self.checkMatchEndowment(principal);
        self.checkTodayShowable(money);
    }
};
tradewin.getScheme = function (money, cycle, lever, fixRate) {
    var interest = 190;
    var discount = false;
    if (money && cycle && lever) {
        if (money >= 1000000) {
            if (cycle >= 3) {
                interest = 160;
            } else if (cycle >= 1) {
                interest = 170;
            }
        } else if (money >= 100000) {
            if (cycle >= 3) {
                interest = 170;
            } else if (cycle >= 1) {
                interest = 180;
            }
        } else if (money >= 1000) {
            if (cycle >= 3) {
                interest = 180;
            } else if (cycle >= 1) {
                interest = 190;
            }
        }
        if (lever <= 2) {
            discount = true;
            interest = interest - (5 - lever + 2) * 10;
            if (fixRate && fixRate > 1 && interest >= fixRate) {
                discount = false;
                interest = fixRate;
            }
        } else if (lever < 5) {
            discount = true;
            interest = interest - (5 - lever + 1) * 10;
            if (fixRate && fixRate > 1 && interest >= fixRate) {
                discount = false;
                interest = fixRate;
            }
        } else if (lever == 5) {
            if (fixRate && fixRate > 1 && interest >= fixRate) {
                interest = fixRate;
            }
        }
    }
    return { discount: discount, interest: interest, openLine: Math.round(money * 1.07), warningLine: Math.round(money * 1.1) };
};
tradewin.getLimit = function(money) {
    if ($.isInt(money)) {
        if (money <= 500000) {
            return "";
        } else if (money <= 1000000) {
            return "单股不超总操盘资金的50%";
        } else {
            return "单股不超总操盘资金的50%（创业板33%）";
        }
    }
    return "";
};
tradewin.checkMatchEndowment = function (principal) {
    var self = this;
    if (principal > 0) {
        var $li = $("#CapitalSelect").find("li");
        $li.removeClass("disable");
        var lever = $.trim($li.filter(".cur").attr('data'));
        for (var i = 2; i <= 6; i++) {
            if (principal * i >self.MaxMoney) {
                $li.eq(i-1).addClass("disable").find("p").attr("class", "");
            }
        }

        if (principal * lever > self.MaxMoney) {
            for (var i = 1; i <= lever; i++) {
                if (principal * i <= self.MaxMoney) {
                    $li.eq(i - 1).click();
                    break;
                }
            }
        }
    }
};
tradewin.getStockData = function () {
    var self = this;
    var matchEndowment =parseInt($("#CapitalSelect").find("li.cur").attr("data"));
    var totalTrade = $("#TotalTrade").html();
    var lossWarLine = $("#LossWarLine").html();
    var lossOpenLine = $("#LossOpenLine").html();
    var loanMoon = $("#LoanMoon").html();
    var startTime = $("input[name=StartTime]:checked").val();
    if (!self.Principal) {
        $.jalert("请输入投资本金");
        return false;
    }
    if (self.Principal % 1000 > 0) {
        $.jalert("投资本金必须是1000的整数倍");
        return false;
    }
    if (self.Principal < self.MinMoney || self.Principal > self.MaxMoney) {
        $.jalert("投资本金" + self.SlfTip);
        return false;
    }
    return {
        Principal: self.Principal,
        MatchEndowment: self.Principal * matchEndowment,
        TotalTrade: $.formatMoneyToDeciamil(totalTrade),
        LossWarLine: $.formatMoneyToDeciamil(lossWarLine),
        LossOpenLine: $.formatMoneyToDeciamil(lossOpenLine),
        LoanMoon: $.formatMoneyToDeciamil(loanMoon),
        FundTime:$("#Cycle").val(),
        StartTime: parseInt(startTime)
    }
};
//#endregion

//#region 登录
var login = {};
login.window = undefined;
login.load= function(callback) {
    var r = "用户名/手机号/邮箱";
    $.StockWindow({
        title: "用户登录", id: "login-window", classes: "login", content: '<label><input type="text" id="UserName"  value="' + r + '" /><span class="icohead"></span></label><label><input type="password" class="pwd" id="Password" value="" /><span class="icolock"></span></label><label><input type="button" id="LoginButton" class="button login" value="登 录"/></label><label class="login-bottom"><a href="/regist/" target="_blank" class="blue">免费注册</a><a href="#" class="blue">忘记密码</a></label>',
        callback: function () {
            $("#UserName").val("").focus();
        }
    });

    $("#UserName").focusin(function () {
        var $this = $(this);
        if ($this.val() == r) {
            $this.val("");
        }
    }).focusout(function () {
        var $this = $(this);
        if ($this.val() == "") {
            $this.val(r);
        }
    });
    $("#Password").focusin(function () {
        var $this = $(this);
        $this.addClass("ui");
    }).focusout(function () {
        var $this = $(this);
        if ($this.val() == "") {
            $this.removeClass("ui");
        }
    });

    var LoginButton = function () {
        var $userName = $("#UserName");
        var $passWord = $("#Password");
        var userName = $.trim($userName.val());
        var passWord = $.trim($passWord.val());
        if (!userName) {
            $.jalert("请填写用户名、手机号或邮箱");
            return;
        }
        if (!passWord) {
            $.jalert("请输入登录密码");
            return;
        }
        $.jajax({
            url: "/login/index",
            params: { userName: userName, passWord: passWord },
            callback: function (ret) {
                if (!ret) {
                    return;
                }
                if (ret.code == 1) {
                    $("#login-window").CloseWindow();
                    callback();
                }
                if (ret.code == 0) {
                    $.jalert(ret.message);
                }
                if (ret.code == 2) {
                    $.jalert(ret.message);
                }
                if (ret.code == 3) {
                    $.jalert(ret.message);
                }
                if (ret.code == 4) {
                    $.jalert(ret.message);
                }

            }
        });
    };

    $("#LoginButton").bind("click", function () {
        LoginButton();
    });

    jQuery.hotkeys.add("return", function () {
        LoginButton();
    });
}
login.init = function () {
    $("#Login").bind("click", function () {
        login.load(function() {
            window.location.reload();
        });
    });
    $(".my").hover(function () {
        var $this = $(this);
        $this.addClass("hover");
        $(".account-info").show();
        $(".whrite-line").show();
    }, function () {
        var $this = $(this);
        $(".account-info").slideUp(200, function() {
            $this.removeClass("hover");
            $(".whrite-line").hide();
        });
    });
}
//#endregion

//#region 弹出框
$.extend({
    StockWindow: function(obj) {
        var title,id,url,content,classes,width,callback;
        title = obj.title;
        id = obj.id;
        url = obj.url;
        content = obj.content;
        classes = obj.classes;
        width = obj.width;
        callback = obj.callback;
        var $id = $("#" + id);
        if ($id.size() > 0) {
            return;
        }
        var html =[];
        html.push('<div class="stock-window ' + classes + '" id="' + id + '" style="' + (width ? "width:" + width + "px" : "") + '">');
        html.push('<dl>');
        html.push('<dt>' + title + '<span id="stock-window-close"></span></dt>');
        html.push('<dd>');
        if (url) {
            html.push('<iframe src=""></iframe>');
        }else if (content) {
            html.push(content);
        } else {

        }
        html.push('</dd>');
        html.push('</dl>');
        html.push('</div>');
        $("body").append('<div class="mask-bg"></div>');
        $("body").append(html.join(""));


        $id = $("#" + id);

        $("#" + id).find("dt>span#stock-window-close").bind("click", function () {
            $(".mask-bg").remove();
            $("#" + id).remove();
        });

        $(window).resize(function() {
            $id.css({
                left: ($(window).width() - $id.outerWidth()) / 2,
                top: ($(window).height() - $id.outerHeight()) / 2 + $(document).scrollTop()
            });
        });

        $(window).resize();

        $(window).scroll(function() {
            $id.css({
                left: ($(window).width() - $id.outerWidth()) / 2,
                top: ($(window).height() - $id.outerHeight()) / 2 + $(document).scrollTop()
            });
        });

        if (callback) {
            callback();
        }
        return $id;
    }
});
$.fn.CloseWindow = function() {
    $(this).remove();
    $(".mask-bg").remove();
};

//#endregion

//#region 功能弹窗
var stockwindow = {}
//图片验证码
stockwindow.PicValidateCode = function(callback) {
   return  $.StockWindow({
        title: "图片验证",
        id: "Checkcode-Window",
        classes: "checkcode",
        content: '<label>输入图片数字&nbsp;&nbsp;<input type="text" id="Checkcode" /><img id="Code" src="/user/ValidateCode" style="float: right" onclick="this.src =\'/user/ValidateCode?\' + new Date().getTime()" ; /></label><label><input type="button" class="button check" value="确  定" /></label>',
        width: 400,
        callback:callback
    });
};

//#region 绑定邮箱
stockwindow.BindMail = function (userId, hideEmail, email) {
    var sendEmail = function ($this,email) {
        $.jajax({
            url: "/user/SendEmail",
            params: { email: email },
            callback: function () {

            }
        });
        $this.attr("disabled", "disabled").attr("class", "btn-normal-disable");
        var i = 60;
        var timer = function () {
            var n = i--;
            $this.val(n + "秒后重新获取");
            if (n == 0) {
                $this.attr("class", "btn-normal").removeAttr("disabled").val("获取邮箱验证码");
                return;
            }
            setTimeout(timer, 1000);
        }
        timer();
    };
    var bind= function() {
        var $BindMail = $.StockWindow({
            title: "绑定邮箱",
            id: "BindMail-Window",
            width: 500,
            content: '<div class="db-m">' +
                    '    <div class="db-con">' +
                    '        <div style="padding:10px 0 20px;" class="ui-sub-form">' +
                    '            <label class="ui-label">邮箱</label><input type="email" id="Email" style="width:180px;" class="ui-input">' +
                    '        </div>' +
                    '        <div class="ui-sub-form">' +
                    '            <label class="ui-label">验证码</label><input type="text" id="CheckCode" style="width:180px;" class="ui-input">' +
                    '            <input type="button" value="获取邮箱验证码" class="btn-normal">' +
                    '        </div>' +
                    '        <div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
                    '            <input type="button" value="提交" class="button red">' +
                    '            <input type="button" value="取消" class="button grey">' +
                    '        </div>' +
                    '    </div>' +
                    '</div>'
        });
        //获取邮箱验证码
        $BindMail.find("input:button.btn-normal").bind("click", function () {
            var $this = $(this);
            var $Email = $BindMail.find("input#Email");
            var newEmail = $Email.val();
            if (!$.trim(newEmail)) {
                $.jalert("邮箱不能为空");
                $Email.focus();
                return;
            }
            sendEmail($this, newEmail);
        });
        //提交
        $BindMail.find("input:button.red").bind("click", function () {
            var $Email = $BindMail.find("input#Email");
            var $CheckCode = $BindMail.find("input#CheckCode");
            var newEmail = $Email.val();
            if (!$.trim(newEmail)) {
                $.jalert("邮箱不能为空");
                $Email.focus();
                return;
            }
            var code = $CheckCode.val();
            if (!$.trim(code)) {
                $.jalert("验证码不能为空");
                $CheckCode.focus();
                return;
            }
            $.jajax({
                url: "/user/BindEmail",
                params: { id: userId, email: newEmail, code: code },
                callback: function (ret) {
                    if (!ret) return;
                    if (ret.code == 0) {
                        $.jalert(ret.message);
                    } else {
                        window.location.reload();
                    }
                }
            });
        });
        //取消
        $BindMail.find("input:button.grey").bind("click", function () {
            $BindMail.CloseWindow();
        });
    }
    var modifyBind = function() {
        var $ModifyBindMail = $.StockWindow({
            title: "修改绑定邮箱",
            id: "ModifyBindMail-Window",
            width: 500,
            content: '<div class="db-m">' +
                    '    <div class="db-con">' +
                    '        <div style="padding:10px 0 20px;" class="ui-sub-form">' +
                    '            <label class="ui-label">原邮箱</label><span class="text">' + hideEmail + '</span>' +
                    '        </div>' +
                    '        <div class="ui-sub-form">' +
                    '            <label class="ui-label">验证码</label><input type="text" id="CheckCode" style="width:180px;" class="ui-input">' +
                    '            <input type="button" value="获取邮箱验证码" id="GetMailCode" class="btn-normal-disable" disabled="disabled">' +
                    '        </div>' +
                    '        <div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
                    '            <input type="button" value="下一步" class="button red">' +
                    '            <input type="button" value="取消" class="button grey">' +
                    '        </div>' +
                    '    </div>' +
                    '</div>'
        });
        //获取邮箱验证码
        $ModifyBindMail.find("input#GetMailCode").bind("click", function () {
            var $this = $(this);
            sendEmail($this, email);
        });
        //下一步
        $ModifyBindMail.find("input:button.red").bind("click", function () {
            var $CheckCode = $ModifyBindMail.find("input#CheckCode");
            var code = $CheckCode.val();
            if (!$.trim(code)) {
                $.jalert("验证码不能为空");
                $CheckCode.focus();
                return;
            }
            $.jajax({
                url: "/user/CheckEmailValidateCode",
                params: { id: userId, email: email, code: code },
                callback: function (ret) {
                    if (!ret) return;
                    if (ret.code == 0) {
                        $.jalert(ret.message);
                    } else {
                        $ModifyBindMail.CloseWindow();
                        bind();
                    }
                }
            });
        });
        //取消
        $ModifyBindMail.find("input:button.grey").bind("click", function () {
            $ModifyBindMail.CloseWindow();
        });
        sendEmail($ModifyBindMail.find("input#GetMailCode"), email);
    };
    if (hideEmail && email) {
        modifyBind();
    } else {
        bind();
    }
};
//#endregion

//#region 实名认证
stockwindow.CardAuthentication = function (userId) {
    var $CardAuthentication = $.StockWindow({
        title: "实名认证",
        id: "CardAuthentication-Window",
        width: 500,
        content:'<div class="db-m">'+
              '<div class="db-tips">'+
              '    <span class="icon icon-warning"></span>'+
              '    <div class="tips">实名信息提交后不可修改，请务必认真填写真实资料<br>一个身份证只能绑定一个帐号<br>如遇到问题，请联系客服 <b>400-8888-566</b></div>' +
              '    </div>'+
              '<div class="db-con">'+
              '    <div style="padding:20px 0;" class="ui-sub-form">'+
              '    <label class="ui-label">真实姓名</label><input type="text" id="UserTrueName" style="width:240px;" class="ui-input">'+
              '    </div>'+
              '    <div class="ui-sub-form">'+
              '    <label class="ui-label">身份证号</label><input type="text" id="UserCard" style="width:240px;" class="ui-input">'+
              '    </div>'+
              '    <div style="padding:20px 0 10px 100px;" class="ui-sub-form">'+
              '    <input type="button" value="提交" class="button red">'+
              '    <input type="button" value="取消" class="button grey">'+
              '    </div>'+
              '    </div>'+
              '</div>'
    });
    $CardAuthentication.find("input:button.grey").bind("click", function () {
        $CardAuthentication.CloseWindow();
    });
    $CardAuthentication.find("input:button.red").bind("click", function () {
        var $UserTrueName = $CardAuthentication.find("#UserTrueName");
        var $UserCard = $CardAuthentication.find("#UserCard");
        var userTrueName = $UserTrueName.val();
        var userCard = $UserCard.val();
        if (!$.trim(userTrueName)) {
            $.jalert("真实姓名不能为空");
            $UserTrueName.focus();
            return;
        }
        if (!$.trim(userCard)) {
            $.jalert("身份证号不能为空");
            $UserTrueName.focus();
            return;
        }
        $.jajax({
            url: "/user/CardAuthentication",
            params: { userId: userId, userTrueName: userTrueName, userCard: userCard },
            callback: function(ret) {
                if (!ret) return;
                if (ret.code == 0) {
                    $.jalert(ret.message);
                } else {
                    window.location.reload();
                }
            }
        });
    });
};
//上传照片
stockwindow.UserPhotos = function (userId) {
    var $UserPhotos = $.StockWindow({
        title: "实名认证—上传照片完成认证",
        id: "UserPhotos-Window",
        width: 500,
        content: '<div class="db-m">' +
            '<div class="db-con">' +
            '    <input type="hidden" value="verifyRealNamePics" name="action"> ' +
            '    <div style="padding:10px 0 10px 20px;" class="ui-sub-form">' +
            '        <label class="ui-label">身份证正面照片</label>' +
            '        <input type="file" class="inp-b">' +
            '    </div>' +
            '    <div style="padding:10px 0 10px 20px;" class="ui-sub-form">' +
            '        <label class="ui-label">身份证背面照片</label><input type="file" class="inp-b w200">' +
            '    </div>' +
            '    <div style="padding:10px 0 10px 20px;" class="ui-sub-form">' +
            '        <label class="ui-label">手持身份证照片</label><input type="file" class="inp-b w200">' +
            '    </div>' +
            '    <div style="position:relative; border:1px dashed #999; padding:20px;" class="clearfix">' +
            '        <div style=" position:absolute; top:-8px; left:60px; width:17px; height:8px; background:url(/images/w.png) no-repeat;">' +
            '        </div>' +
            '        <a target="_blank" href="#">' +
            '            <img width="150" height="115" class="fl" src="">' +
            '        </a>' +
            '        <div class="ex">' +
            '        <b class="f16">手持身份证照片示例</b>' +
            '        <br>' +
            '        本人的脸部和身份证文字<br>必须在照片内清晰可见' +
            '        </div>' +
            '        </div>' +
            '    <div style="padding:30px 0 10px; text-align:center;" class="ui-sub-form">' +
            '        <input type="button" value="上传" class="button red">' +
            '        <input type="button" value="暂不上传" class="button grey">' +
            '        </div>' +
            '    </div>' +
            '</div>'
    });
    $UserPhotos.find("input:button.grey").bind("click", function () {
        $UserPhotos.CloseWindow();
    });
    var files = {};
    $UserPhotos.find("input:file").eq(0).bind("change", function () {
        var $this = $(this);
        if (!$this.val()) {
            return;
        }
        files[1]=$this[0].files[0];
    });
    $UserPhotos.find("input:file").eq(1).bind("change", function () {
        var $this = $(this);
        if (!$this.val()) {
            return;
        }
        files[2] = $this[0].files[0];
    });
    $UserPhotos.find("input:file").eq(2).bind("change", function () {
        var $this = $(this);
        if (!$this.val()) {
            return;
        }
        files[3] = $this[0].files[0];
    });
    $UserPhotos.find("input:button.red").bind("click", function () {
        if (!files[1]) {
            $.jalert("请上传身份证正面照片");
            return;
        }
        if (!files[2]) {
            $.jalert("请上传身份证背面照片");
            return;
        }
        if (!files[3]) {
            $.jalert("请上传手持身份证照片");
            return;
        }
        var data = new FormData();
        data.append("userId", userId);
        var i = 0;
        for(var k in files) {
            data.append("files" + i, files[k]);
            i++;
        }
        if (i == 0) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', "/user/UploadPhoto", true);
        xhr.onload = function (e) {
            if (this.status == 200) {
               window.location.reload();
            }
        };
        xhr.send(data);
    });
};
//#endregion

//#region 修改绑定手机
stockwindow.BindPhone = function(phone,hidePhone, userId) {
    //发送短信验证码
    var sendMessageCode = function($obj) {
        $.jajax({
            url: "/user/SendLockCode",
            params: { phone: phone },
            callback: function(ret) {
                if (ret) {

                }
            }
        });
        $obj.attr("disabled", "disabled").attr("class", "btn-normal-disable");
        var i = 60;
        var timer = function() {
            var n = i--;
            $obj.val(n + "秒后重新获取");
            if (n == 0) {
                $obj.attr("class", "btn-normal").removeAttr("disabled").val("获取短信验证码");
                return;
            }
            setTimeout(timer, 1000);
        }
        timer();
    };
    var bindNewPhone = function () {
        var checkPhone = function() {
            var $Phone = $("#UserPhone");
            var newPhone = $.trim($Phone.val());
            if (!newPhone) {
                $.jalert("手机号码不能为空");
                $Phone.focus();
                return false;
            }
            var reg = /^(\({0,1}\d{3,4})\){0,1}(-){0,1}(\d{7,8})$/;
            if (!reg.test(newPhone)) {
                $.jalert("手机号码格式错误");
                $Phone.focus();
                return false;
            }
            return newPhone;
        };
        //绑定新手机号
        var $BindNewPhoneWindow = $.StockWindow({
            title: "绑定新手机",
            id: "BindNewPhoneWindow",
            width: 500,
            content: '<div class="db-m">' +
                '<div class="db-con">' +
                '<div style="padding:10px 0 20px;" class="ui-sub-form">' +
                '<label class="ui-label">新手机号码</label><input type="tel" id="UserPhone" style="width:180px;" class="ui-input">' +
                '</div>' +
                '<div class="ui-sub-form">' +
                '<label class="ui-label">验证码</label><input type="text" id="CheckCode" style="width:180px;" class="ui-input">' +
                '<input type="button" id="NewGetLockCode" value="获取验证码" class="btn-normal">' +
                '</div>' +
                '<div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
                '<input type="button" value="提交" class="button red">' +
                '<input type="button" value="取消" class="button grey">' +
                '</div>' +
                '</div>' +
                '</div>',
            callback: function () {
                var $GetLockCode = $("#NewGetLockCode");
                $GetLockCode.bind("click", function () {
                    var $this = $(this);
                    if (!checkPhone()) {
                        return;
                    }
                    var $CheckcodeWindow = stockwindow.PicValidateCode(function () {
                        var $Checkcode = $("#Checkcode-Window");
                        $Checkcode.find("input.button").bind("click", function () {
                            var code = $Checkcode.find("#Checkcode").val();
                            if (!code) {
                                $.jalert("请输入图片中的数字");
                                return;
                            }
                            $.jajax({
                                url: "/user/CheckValidateCode",
                                params: { code: code },
                                callback: function (ret) {
                                    if (ret && ret.data) {
                                        //#region 发送手机短信验证码
                                        sendMessageCode($this);
                                        $CheckcodeWindow.CloseWindow();
                                        //#endregion
                                    } else {
                                        $.jalert("验证码错误");
                                    }
                                }
                            });
                        });
                    });
                });
            }
        });
        //取消绑定新手机号
        $BindNewPhoneWindow.find("input:button.grey").bind("click", function () {
            $BindNewPhoneWindow.CloseWindow();
        });
        //确定绑定新手机号
        $BindNewPhoneWindow.find("input:button.red").bind("click", function () {
            var $this = $(this);
            var newPhone = checkPhone();
            if (!newPhone) {
                return;
            }
            var $CheckCode = $BindNewPhoneWindow.find("input:text#CheckCode");
            var checkCode = $.trim($CheckCode.val());
            if (!checkCode) {
                $.jalert("请输入短信验证码");
                $CheckCode.focus();
                return;
            }
            $.jajax({
                url: "/user/UpdatePhone",
                params: { userId: userId, phome: newPhone, code: checkCode },
                callback: function (ret) {
                    if (ret && ret.code) {
                        $BindNewPhoneWindow.CloseWindow();
                        window.location.reload();
                    } else {
                        $.jalert(ret.message);
                    }
                }
            });
        });
    };

    var $BindPhoneWindow = $.StockWindow({
        title: "修改绑定手机",
        id: "BindPhoneWindow",
        width: 500,
        content: '<div class="db-m">' +
            '<div class="db-con">' +
            '<div style="padding:10px 0 20px;" class="ui-sub-form">' +
            '<label class="ui-label">原手机号码</label><span class="text">' + hidePhone + '</span>' +
            '</div>' +
            '<div class="ui-sub-form">' +
            '<label class="ui-label">验证码</label><input type="text" id="CheckCode" style="width:180px;" class="ui-input">' +
            '<input type="button" value="获取短信验证码" id="GetLockCode" class="btn-normal-disable" disabled="disabled">' +
            '</div>' +
            '<div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
            '<input type="button" value="下一步" class="button red">' +
            '<input type="button" value="取消" class="button grey">' +
            '</div>' +
            '</div>' +
            '</div>',
        callback: function() {
            var $GetLockCode = $("#GetLockCode");
            sendMessageCode($GetLockCode);
            $GetLockCode.bind("click", function() {
                var $this = $(this);
                var $CheckcodeWindow = stockwindow.PicValidateCode(function() {
                    var $Checkcode = $("#Checkcode-Window");
                    $Checkcode.find("input.button").bind("click", function() {
                        var code = $Checkcode.find("#Checkcode").val();
                        if (!code) {
                            $.jalert("请输入图片中的数字");
                            return;
                        }
                        $.jajax({
                            url: "/user/CheckValidateCode",
                            params: { code: code },
                            callback: function(ret) {
                                if (ret && ret.data) {
                                    //#region 发送手机短信验证码
                                    sendMessageCode($this);
                                    $CheckcodeWindow.CloseWindow();
                                    //#endregion
                                } else {
                                    $.jalert("验证码错误");
                                }
                            }
                        });
                    });
                });
            });
        }
    });
    $BindPhoneWindow.find("input:button.grey").bind("click", function() {
        $BindPhoneWindow.CloseWindow();
    });
    $BindPhoneWindow.find("input:button.red").bind("click", function() {
        var $CheckCode = $BindPhoneWindow.find("input:text#CheckCode");
        var checkCode = $.trim($CheckCode.val());
        if (!checkCode) {
            $.jalert("请输入短信验证码");
            $CheckCode.focus();
            return;
        }
        $.jajax({
            url: "/user/CheckSendLockCode",
            params: { code: checkCode },
            callback: function(ret) {
                if (!ret || !ret.data) {
                    $CheckCode.focus();
                    $.jalert("短信验证码错误");
                } else {
                    $BindPhoneWindow.CloseWindow();
                    bindNewPhone();
                }
            }
        });
    });
};
//#endregion

//登录密码
stockwindow.LoginPassword = function (userId) {
    var $LoginPassword = $.StockWindow({
        title: "修改登录密码",
        id: "LoginPassword-Window",
        width:500,
        content: '<div class="db-m">' +
            '    <div class="db-con">' +
            '        <div style="padding:10px 0;" class="ui-sub-form">' +
            '            <label class="ui-label">原登录密码</label><input type="password" id="OldPassword" style="width:200px;" class="ui-input">' +
            '        </div>' +
            '        <div style="padding:10px 0 20px;" class="ui-sub-form">' +
            '            <label class="ui-label">新登录密码</label><input type="password" id="NewPassword1"  style="width:200px;" class="ui-input">' +
            '        </div>' +
            '        <div class="ui-sub-form">' +
            '            <label class="ui-label">确认新登录密码</label><input type="password" id="NewPassword2"  style="width:200px;" class="ui-input">' +
            '        </div>' +
            '        <div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
            '            <input type="button" value="确认" class="button red">' +
            '            <input type="button" value="取消" class="button grey">' +
            '        </div>' +
            '    </div>' +
            '</div>'
    });
    $LoginPassword.find("input:button.grey").bind("click", function () {
        $LoginPassword.CloseWindow();
    });
    $LoginPassword.find("input:button.red").bind("click", function () {
        var $OldPassword = $LoginPassword.find("input#OldPassword");
        var $NewPassword1 = $LoginPassword.find("input#NewPassword1");
        var $NewPassword2 = $LoginPassword.find("input#NewPassword2");
        var oldPassword = $OldPassword.val();
        var newPassword1 = $NewPassword1.val();
        var newPassword2 = $NewPassword2.val();
        if (!$.trim(oldPassword)) {
            $.jalert("原登录密码不能为空");
            $OldPassword.focus();
            return;
        }
        if (!$.trim(newPassword1)) {
            $.jalert("新登录密码不能为空");
            $NewPassword1.focus();
            return;
        }
        if (!$.trim(newPassword2)) {
            $.jalert("确认新登录密码不能为空");
            $NewPassword2.focus();
            return;
        }
        if (newPassword2!=newPassword1) {
            $.jalert("两次输入的密码不一致");
            $NewPassword1.focus();
            return;
        }
        $.jajax({
            url: "/user/UpdateLoaginPassword",
            params: { userId:userId, oldPassword:oldPassword, newPassword1:newPassword1, newPassword2:newPassword2},
            callback: function(ret) {
                if (!ret) return;
                if (ret.code == 0) {
                    $.jalert(ret.message);
                } else {
                    $LoginPassword.CloseWindow();
                    window.location.reload();
                }
            }
        });
    });
};

//提款密码
stockwindow.DrawingPassword = function (userId) {
    var $DrawingPassword = $.StockWindow({
        title: "设置提现密码",
        id: "DrawingPassword-Window",
        width: 500,
        content: '<div class="db-m">'+
                '    <div class="db-con">'+
                '        <div style="padding:10px 0 20px;" class="ui-sub-form">'+
                '            <label class="ui-label">提现密码</label><input id="DrawingPassword1" type="password" style="width:200px;" class="ui-input">' +
                '        </div>'+
                '        <div class="ui-sub-form">'+
                '            <label class="ui-label">确认提现密码</label><input id="DrawingPassword2" type="password" style="width:200px;" class="ui-input">' +
                '        </div>'+
                '        <div style="padding:20px 0 10px 100px;" class="ui-sub-form">'+
                '            <input type="button" value="确认" class="button red">'+
                '            <input type="button" value="取消" class="button grey">'+
                '        </div>'+
                '    </div>' +
                '</div>'
    });
    $DrawingPassword.find("input:button.grey").bind("click", function () {
        $DrawingPassword.CloseWindow();
    });
    $DrawingPassword.find("input:button.red").bind("click", function () {
        var $DrawingPassword1 = $DrawingPassword.find("input#DrawingPassword1");
        var $DrawingPassword2 = $DrawingPassword.find("input#DrawingPassword2");
        var drawingPassword1 = $DrawingPassword1.val();
        var drawingPassword2 = $DrawingPassword2.val();
        if (!$.trim(drawingPassword1)) {
            $.jalert("提现密码不能为空");
            $DrawingPassword1.focus();
            return;
        }
        if (!$.trim(drawingPassword2)) {
            $.jalert("确认提现密码不能为空");
            $DrawingPassword2.focus();
            return;
        }
        if (drawingPassword1!=drawingPassword2) {
            $.jalert("两次输入的密码不一致");
            $DrawingPassword1.focus();
            return;
        }
        $.jajax({
            url: "/user/SetDrawingPassword",
            params: {userId:userId,password1:drawingPassword1,password2:drawingPassword2},
            callback: function(ret) {
                if (!ret) return;
                if (ret.code == 0) {
                    $.jalert(ret.message);
                } else {
                    $DrawingPassword.CloseWindow();
                    window.location.reload();
                }
            }
        });
    });
};
//修改提款密码
stockwindow.ModifyDrawingPassword = function(userId) {
    var $ModifyDrawingPassword = $.StockWindow({
        title: "修改提现密码",
        id: "DrawingPassword-Window",
        width: 500,
        content: '<div class="db-m">' +
            '    <div class="db-con">' +
            '        <div style="padding:10px 0;" class="ui-sub-form">' +
            '            <label class="ui-label">原提现密码</label><input type="password" id="OldDrawingPassword" style="width:200px;" class="ui-input">' +
            '        </div>' +
            '        <div style="padding:10px 0 20px;" class="ui-sub-form">' +
            '            <label class="ui-label">新提现密码</label><input type="password" id="DrawingPassword1" style="width:200px;" class="ui-input">' +
            '        </div>' +
            '        <div class="ui-sub-form">' +
            '            <label class="ui-label">确认新提现密码</label><input type="password"  id="DrawingPassword2" style="width:200px;" class="ui-input">' +
            '        </div>' +
            '        <div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
            '            <input type="button" value="确认" class="button red">' +
            '            <input type="button" value="取消" class="button grey">' +
            '        </div>' +
            '    </div>' +
            '</div>'
    });
    $ModifyDrawingPassword.find("input:button.grey").bind("click", function () {
        $ModifyDrawingPassword.CloseWindow();
    });
    $ModifyDrawingPassword.find("input:button.red").bind("click", function () {
        var $OldDrawingPassword = $ModifyDrawingPassword.find("input#OldDrawingPassword");
        var $DrawingPassword1 = $ModifyDrawingPassword.find("input#DrawingPassword1");
        var $DrawingPassword2 = $ModifyDrawingPassword.find("input#DrawingPassword2");
        var oldDrawingPassword = $OldDrawingPassword.val();
        var drawingPassword1 = $DrawingPassword1.val();
        var drawingPassword2 = $DrawingPassword2.val();
        if (!$.trim(oldDrawingPassword)) {
            $.jalert("原提现密码不能为空");
            $OldDrawingPassword.focus();
            return;
        }
        if (!$.trim(drawingPassword1)) {
            $.jalert("提现密码不能为空");
            $DrawingPassword1.focus();
            return;
        }
        if (!$.trim(drawingPassword2)) {
            $.jalert("确认提现密码不能为空");
            $DrawingPassword2.focus();
            return;
        }
        if (drawingPassword1 != drawingPassword2) {
            $.jalert("两次输入的密码不一致");
            $DrawingPassword1.focus();
            return;
        }
        $.jajax({
            url: "/user/UpdateDrawingPassword",
            params: { userId: userId, oldPassword: oldDrawingPassword, password1: drawingPassword1, password2: drawingPassword2 },
            callback: function (ret) {
                if (!ret) return;
                if (ret.code == 0) {
                    $.jalert(ret.message);
                } else {
                    $ModifyDrawingPassword.CloseWindow();
                    window.location.reload();
                }
            }
        });
    });
};
//忘记提款密码
stockwindow.FindDrawingPassword = function (userId, hidePhone, phone) {
    //发送短信验证码
    var sendMessageCode = function ($obj) {
        $.jajax({
            url: "/user/SendLockCode",
            params: { phone: phone },
            callback: function (ret) {
                if (ret) {

                }
            }
        });
        $obj.attr("disabled", "disabled").attr("class", "btn-normal-disable");
        var i = 60;
        var timer = function () {
            var n = i--;
            $obj.val(n + "秒后重新获取");
            if (n == 0) {
                $obj.attr("class", "btn-normal").removeAttr("disabled").val("获取短信验证码");
                return;
            }
            setTimeout(timer, 1000);
        }
        timer();
    };

    var $FindDrawingPassword = $.StockWindow({
        title: "忘记提现密码",
        id: "DrawingPassword-Window",
        width: 500,
        content: '<div class="db-m">' +
            '   <div class="db-con">' +
            '       <div style="padding:10px 0 20px;" class="ui-sub-form">' +
            '           <label class="ui-label">手机</label><span class="text">'+hidePhone+'</span>' +
            '       </div>' +
            '       <div class="ui-sub-form">' +
            '           <label class="ui-label">验证码</label><input id="CheckCode" type="text" style="width:180px;" class="ui-input">' +
            '           <input type="button" id="GetCode" value="60秒后重新获取" class="btn-normal-disable" disabled="disabled">' +
            '       </div>' +
            '       <div style="padding:20px 0 10px 100px;" class="ui-sub-form">' +
            '           <input type="button" value="下一步" class="button red">' +
            '           <input type="button" value="取消" class="button grey">' +
            '       </div>' +
            '   </div>' +
            '</div>',
        callback: function () {
            var $GetCode = $("input#GetCode");
            sendMessageCode($GetCode);
            $GetCode.bind("click", function() {
                sendMessageCode($(this));
            });
        }
    });
    $FindDrawingPassword.find("input:button.grey").bind("click", function () {
        $FindDrawingPassword.CloseWindow();
    });
    $FindDrawingPassword.find("input:button.red").bind("click", function () {
        var $CheckCode = $FindDrawingPassword.find("input:text#CheckCode");
        var checkCode = $.trim($CheckCode.val());
        if (!checkCode) {
            $.jalert("请输入短信验证码");
            $CheckCode.focus();
            return;
        }
        $.jajax({
            url: "/user/CheckSendLockCode",
            params: { code: checkCode },
            callback: function (ret) {
                if (!ret || !ret.data) {
                    $CheckCode.focus();
                    $.jalert("短信验证码错误");
                } else {
                    $FindDrawingPassword.CloseWindow();
                    stockwindow.DrawingPassword(userId);
                }
            }
        });
    });
};
//#endregion
